package cn.lh.org.service.impl;

import cn.lh.basic.mapper.BaseMapper;
import cn.lh.basic.service.impl.BaseServiceImpl;
import cn.lh.org.domain.Department;
import cn.lh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private BaseMapper<Department> baseMapper;

    @Override
    @Transactional
    public void add(Department department) {
        baseMapper.save(department);
        update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        if (department.getParent_id() == null) {
            department.setDirPath("/" + department.getId());
        } else {
            Department parentDepartment = baseMapper.loadById(department.getParent_id());
            department.setDirPath(parentDepartment.getDirPath()+"/"+department.getId());
        }
        baseMapper.update(department);
    }

    @Override
    public List<Department> getDepartmentTree() {
        List<Department> departmentTree = baseMapper.loadAll().stream().filter(department -> department.getParent() == null).collect(Collectors.toList());
        return departmentTree;
    }
}
